<!-- 心理测评管理 -->
<template>
	<div>
		<!-- <el-breadcrumb :separator-icon="ArrowRight">
			<el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>心理测评</el-breadcrumb-item>
			<el-breadcrumb-item>心理测评管理</el-breadcrumb-item>
		</el-breadcrumb>
		<hr /> -->
		<BreadCrumb pathOne="心理测评" pathTwo="测评问题管理" ></BreadCrumb>

		<!-- 头部搜索栏 -->
		<div>
			<el-form :inline="true" :model="formInline" class="demo-form-inline">
				<el-form-item label="题目名称">
					<el-input v-model="formInline.evaluationName" placeholder="请输入题目名称" clearable
						@clear="handleClear1()" />
				</el-form-item>

				<el-form-item>
					<el-button type="primary" @click="getData">搜索</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="addData">新增题目</el-button>
				</el-form-item>
				

			</el-form>

			<!-- 新增弹窗 -->
			<el-dialog v-model="add" title="新增题目" width="730px" @close="close">
			  <el-form :model="addForm" label-width="120px">
			    <!-- 题目名称 -->
				<el-form-item label="测评名称">
					<el-select v-model="inline.evaluateName" placeholder="请选择测评" clearable @clear="handleClear3()">
						<el-option v-for="(option,index) in list" :key="option.index"
							:value="option.evaluateName" />
					</el-select>
				</el-form-item>
			    <el-form-item label="题目名称">
			      <el-input v-model="addForm.questionText" placeholder="请输入测评题目" />
			    </el-form-item>
						
			    <!-- 选项及得分 -->
			    <el-form-item label="选项内容">
			      <!-- 循环渲染 4 个选项 -->
			      <div v-for="(option, index) in addForm.evaluateOptions" :key="index" class="option-item">
			        <el-input 
			          v-model="option.optionText" 
			          :placeholder="`请输入第 ${index + 1} 个选项内容`" 
			          style="width: 200px; margin-right: 10px;"
			        />
			        <el-input-number 
			          v-model="option.score" 
			          :min="1" 
			          label="选项得分" 
			          style="width: 120px; margin-right: 20px;"
			        />
			      </div>
			    </el-form-item>
			  </el-form>
						
			  <template #footer>
			    <div class="dialog-footer">
			      <el-button @click="addNo()">取消</el-button>
			      <el-button type="primary" @click="addYes()">确定</el-button>
			    </div>
			  </template>
			</el-dialog>
			
			<!-- 编辑弹窗 -->
			    <el-dialog v-model="edit" title="修改题目" width="730px">
					<el-form-item label="测评名称">
						<el-select v-model="editInline.evaluateName" placeholder="请选择测评" clearable @clear="handleClear3()">
							<el-option v-for="(option,index) in evaluateList" :key="option.index"
								:value="option.evaluateName" />
						</el-select>
					</el-form-item>
			      <el-form :model="editForm" label-width="120px">
			        <!-- 题目名称 -->
			        <el-form-item label="题目名称">
			          <el-input v-model="editForm.questionText" placeholder="请输入测评题目" />
			        </el-form-item>
			
			        <!-- 选项及得分 -->
			        <el-form-item label="选项内容">
			          <!-- 循环渲染 4 个选项 -->
			          <div v-for="(option, index) in editForm.evaluateOptions" :key="index" class="option-item">
			            <el-input 
			              v-model="option.optionText" 
			              :placeholder="`请输入第 ${index + 1} 个选项内容`" 
			              style="width: 200px; margin-right: 10px;"
			            />
			            <el-input-number 
			              v-model="option.score" 
			              :min="1" 
			              label="选项得分" 
			              style="width: 120px; margin-right: 20px;"
			            />
			          </div>
			        </el-form-item>
			      </el-form>
			
			      <template #footer>
			        <div class="dialog-footer">
			          <el-button @click="editNo()">取消</el-button>
			          <el-button type="primary" @click="editYes()">确定</el-button>
			        </div>
			      </template>
			    </el-dialog>


		</div>


		<!-- 表格数据展示 -->
		<div>
			<el-table :data="tableData" border @selection-change="handleSelectionChange" style="width: 100%;">
			  <el-table-column :selectable="selectable" type="selection" width="55" />
			  <el-table-column label="ID" width="120">
			    <template #default="scope">{{ scope.row.id }}</template>
			  </el-table-column>
			  
			  <el-table-column property="questionText" label="题目名称" />
			  
			  <!-- 选项内容分组列 -->
			  <el-table-column label="选项内容" header-align="center">
			    <el-table-column prop="evaluateOptions[0].optionText" label="A选项" />
			    <el-table-column prop="evaluateOptions[1].optionText" label="B选项" />
			    <el-table-column prop="evaluateOptions[2].optionText" label="C选项" />
			    <el-table-column prop="evaluateOptions[3].optionText" label="D选项" />
			  </el-table-column>
			  
			  <!-- 选项得分分组列 -->
			  <el-table-column label="选项得分" header-align="center">
			    <el-table-column prop="evaluateOptions[0].score" label="A选项得分" width="100"/>
			    <el-table-column prop="evaluateOptions[1].score" label="B选项得分" width="100"/>
			    <el-table-column prop="evaluateOptions[2].score" label="C选项得分" width="100"/>
			    <el-table-column prop="evaluateOptions[3].score" label="D选项得分" width="100"/>
			  </el-table-column>
			
			  <!-- 操作列 -->
			  <el-table-column label="操作" width="120">
			    <template #default="scope">
			      <el-button type="primary" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
			    </template>
			  </el-table-column>
			</el-table>
		</div>


		<!-- 分页设置 -->
		<div>
			<el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]"
				:size="size" :disabled="disabled" :background="background"
				layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
				@current-change="handleCurrentChange" />
		</div>
	</div>
</template>

<script setup>
	import {
		getCurrentInstance,
		onMounted,
		reactive,
		ref
	} from 'vue'
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus'
	import {
		Plus
	} from '@element-plus/icons-vue'
	// evaluation/page?evaluationName=&evaluationIntro=&pageNum=1&pageSize=10&classifyName=
	import BreadCrumb from "../../components/BreadCrumb.vue"

	// 设置表单元素接收数据
	const formInline = reactive({
		evaluationName: '',
		evaluationIntro: '',
		classifyName: '',
	})
	const nameList = reactive([{}])

	// 设置表格接收数据
	const tableData = ref([])


	// 页面挂载后加载数据
	onMounted(() => {
		getData(),
			getClass()
	})

	// 清除输入框自动搜索
	const handleClear1 = () => {
		formInline.evaluationName = ''
		getData()
	};
	// const handleClear2 = () => {
	// 	formInline.evaluationIntro = ''
	// 	getData()
	// };
	// const handleClear3 = () => {
	// 	formInline.classifyName = ''
	// 	getData()
	// };

	//新增
	const add = ref(false)
	const addForm = reactive({
		evaluateId:'',
		questionText:'',
		evaluateOptions:[
			{
				optionText:'',
				score:1,
			},
			{
				optionText:'',
				score:1,
			},
			{
				optionText:'',
				score:1,
			},
			{
				optionText:'',
				score:1,
			}
		]
	})
	const list = ref([])
	const inline = reactive({
		id:'',
		evaluateName:''
	})
	const addData = () => {
	  add.value = true;  // 修改为分号
	  axios.get(`evaluate`)
	    .then((resp) => {
	      console.log(resp.data.list);
	      if (resp.code === 200) {  // 使用 === 更严格的比较
	        list.value = resp.data;
	      } else {
	        ElMessage.error(resp.message);  // 移除多余的右括号
	      }
	    })  // 修正括号位置
	    .catch((error) => {
	      console.error('Error:', error);
	      ElMessage.error('请求失败，请稍后再试');
	    })
	   //  .finally(() => {
	   //    // 如果 getData 是组件方法，确保正确调用
	   //    // 对于 Vue 3 组合式 API，可能需要从上下文中获取
	   //    // 或者直接调用函数（如果在同一个模块中定义）
	   //    // 移除 this
		  // for(let	 i=0; i<list.length; i++){
			 //  if(inline.evaluateName === list[i].evaluateName){
				//   inline.id = list[i].id;
				//   addForm.evaluateId = inline.id;
				//   break;
			 //  }
		  // }
	   //  });  // 修正括号位置
	};
	const addYes = () => {
		for(let	 i=0; i<list.value.length; i++){
					  if(inline.evaluateName === list.value[i].evaluateName){
						  inline.id = list.value[i].id;
						  addForm.evaluateId = inline.id;
						  break;
					  }
		}
		axios.post('evaluateQuestion',addForm).then((resp) => {
			if (resp.code == 200) {
				ElMessage({
					message: resp.message,
					type: 'success',
				});
			} else {
				ElMessage.error(resp.message);
			}
		}).catch((error) => {
				console.error('Error:', error);
				ElMessage.error('请求失败，请稍后再试');
			})
			.finally(() => {
				inline.evaluateName = '';
				add.value = false;
				addForm.questionText= '',
				addForm.evaluateOptions=[
					{
						optionText:'',
						score:1,
					},
					{
						optionText:'',
						score:1,
					},
					{
						optionText:'',
						score:1,
					},
					{
						optionText:'',
						score:1,
					}
				]
				getData()
			})
	}
	const addNo = () =>{
		
		inline.evaluateName = '';
		add.value=false,
		ElMessage('取消新增')
		addForm.questionText='',
		addForm.evaluateOptions=[
			{
				optionText:'',
				score:1,
			},
			{
				optionText:'',
				score:1,
			},
			{
				optionText:'',
				score:1,
			},
			{
				optionText:'',
				score:1,
			}
		]
	}
	const close = () => {
		inline.evaluateName = '';
		addForm.questionText='',
		addForm.evaluateOptions=[
			{
				optionText:'',
				score:1,
			},
			{
				optionText:'',
				score:1,
			},
			{
				optionText:'',
				score:1,
			},
			{
				optionText:'',
				score:1,
			}
		]
	}

	// 编辑与删除
	const evaluateList = ref([])
	const edit = ref(false)
	const editForm = reactive({
		evaluateId:'',
		questionText:'',
		evaluateOptions:[]
	})
	const editInline = reactive({
		id:'',
		evaluateName:''
	})
	const handleEdit = (row) => {
		edit.value = true
		axios.get(`evaluate`)
		  .then((resp) => {
		    console.log(resp.data.list);
		    if (resp.code === 200) {  // 使用 === 更严格的比较
		      evaluateList.value = resp.data;
		    } else {
		      ElMessage.error(resp.message);  // 移除多余的右括号
		    }
		  })  // 修正括号位置
		  .catch((error) => {
		    console.error('Error:', error);
		    ElMessage.error('请求失败，请稍后再试');
		  })
		  
		axios.get(`evaluateQuestion/${row.id}`).then((resp) => {
			Object.assign(editForm, resp.data);
			console.log("==============")
			console.log(editForm)
			for(let i=0; i<evaluateList.value.length;i++){
				if(resp.data.evaluateId === evaluateList.value[i].id){
					editInline.evaluateName = evaluateList.value[i].evaluateName;
					break;
				}
			}
		})
		.catch((error) => {
			console.error('Error:', error);
			ElMessage.error('请求失败，请稍后再试');
		 })
		// .finally(() => {
		// 	for(let i = 0; i < list.value.length; i++){
		// 		if(editInline.evaluateName === list.value[i].evaluateName){
		// 			editInline.id = list.value[i].id,
		// 			editForm.evaluateId = editInline.ids
		// 		}
		// 	}
		// })
	}
	const editNo = () => {
	    edit.value = false;
	    ElMessage('取消编辑');
	};
	const editYes = () => {
		for(let	 i=0; i<evaluateList.value.length; i++){
					  if(editInline.evaluateName === evaluateList.value[i].evaluateName){
						  editInline.id = evaluateList.value[i].id;
						  editForm.evaluateId = editInline.id;
						  break;
					  }
		}
		axios.put('evaluateQuestion', editForm).then((resp) => {
				if (resp.code == 200) {
					ElMessage({
						message: resp.message,
						type: 'success',
					});
				} else {
					ElMessage.error(resp.message);
				}
			})
			.catch((error) => {
				console.error('Error:', error);
				ElMessage.error('请求失败，请稍后再试');
			})
			.finally(() => {
				edit.value = false;
				getData()
			})
	};



	// 设置分页
	const currentPage = ref(1)
	const pageSize = ref(10)
	const total = ref(0)
	const handleSizeChange = (val) => {
		console.log(`${val} items per page`)
		pageSize.value = val
		getData()
	}
	const handleCurrentChange = (val) => {
		console.log(`current page: ${val}`)
		currentPage.value = val
		getData()
	}





	// 获取axios对象实例发送请求
	const axios = getCurrentInstance().appContext.config.globalProperties.axios;
	// 获取表单数据
	const getData = () => {
		axios.get(
				`evaluateQuestion/page?questionText=${formInline.evaluationName}&pageNum=${currentPage.value}&pageSize=${pageSize.value}`
			)
			.then((resp) => {
				total.value = resp.data.total
				console.log(resp.data.list.length, 'fjskdfhjsakhdfkj');
				console.log(resp.data);

				tableData.value = resp.data.list
			})
	}
	// 获取分类数据
	const getClass = () => {
		axios.get('evaluationClassify').then((resp) => {
			nameList.splice(0, nameList.length, ...resp.data)
			console.log("naemList", nameList[0].id);

		})
	}
</script>

<style scoped>
	.demo-form-inline .el-input {
		--el-input-width: 220px;
	}

	.demo-form-inline .el-select {
		--el-select-width: 220px;
	}

	/* 图片显示 */
	.block {
		/* border: 1px solid #ccc; */
		width: 100px;
		height: 100px;
		background-color: rgb(245, 247, 250);
		text-align: center;
		line-height: 100px;
	}

	/* 文件上传 */
	.avatar-uploader .avatar {
		width: 150px;
		height: 150px;
		display: block;
		border-radius: 5px;
		margin-right: 5px;
	}

	.avatar-uploader .el-upload {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		background-color: rgb(251, 253, 255);
		font-size: 28px;
		color: #8c939d;
		width: 150px;
		height: 150px;
		text-align: center;
		border: 1px dashed rgb(192, 204, 218);
		border-radius: 5px;
	}
</style>